package com.woniuxy.movie.gateway.exception;

import cn.hutool.json.JSONUtil;
import com.woniuxy.movie.commons.core.exception.MovieException;
import com.woniuxy.movie.commons.core.model.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GloableExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        throwable.printStackTrace();
        //设置错误信息
        Result<Boolean> result = Result.getResult(Boolean.class).setCode(500).setMsg("系统异常").setData(false);
        if (throwable instanceof MovieException){
            MovieException ex = (MovieException) throwable;
            result.setCode(ex.getCode()).setMsg(ex.getMessage());
        }
        //设置JSON格式响应
        serverWebExchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_PDF);
        String resultJson = JSONUtil.toJsonStr(result);
        //响应错误信息
        /*return serverWebExchange.getResponse()
                .writeWith(Mono.fromSupplier(() -> serverWebExchange.getResponse()
                        .bufferFactory().wrap(resultJson.getBytes(StandardCharsets.UTF_8))));*/
        return serverWebExchange.getResponse().writeWith(Mono.fromSupplier(()->{
            return serverWebExchange.getResponse().bufferFactory().wrap(resultJson.getBytes());
        }));
    }
}
